<%@ page language="java" contentType="text/html;" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc_jqgrid.jsp"></jsp:include>
<link rel="stylesheet" href="${ctx}/css/common.css" />
<link rel="stylesheet"  href="${ctx}/css/skBook.css"/>
<link rel="stylesheet"  href="${ctx}/css/orderPassengerWait.css"/>
<script type="text/javascript">
$(function(){
    layer.load();
	$.ajax({
		type:'get',
		url:'${ctx}/order/orderDetail/${orderNumber}',
		dataType:'json',
		success:function(data){
            layer.closeAll();
			if(data.success){
				//alert(data.obj.toStartAirport);
				initPage(data.obj);
			}
			else{
				layer.alert(data.msg);
			}
		},
		error:function(msg){
            layer.closeAll();
			layer.alert("请检查您的网络连接，然后重试！");
		}
	});
    //加载旅客信息
    $("#jqGrid").jqGrid({
        url:'${ctx}/order/queryPassenger/${orderNumber}?temp='+Math.random(),
        mtype: "GET",
        datatype: "json",
        shrinkToFit: true,//按比例初始化列宽度
        viewrecords: true,//是否要显示总记录数
        rownumbers: true,//显示行顺序号
        rownumWidth: 35,//顺序号宽度
        //multiselect: true,//定义是否可以多选
        //multiboxonly: true,//为ture时只有选择checkbox才会起作用
        height : '100%', //"100%"
        rowNum: 500,//每页行数
        rowList : [ 500 ],//调整表格显示的记录数
        width: 1300,
        caption: "",//标题
        colModel: [
            { label: 'Id', name: 'id', key: true, width: 75,hidden:true  },
            { label: '票号', name: 'ticketNumber',  width: 100,hidden:true },
            { label: '', name: 'lastName_en', width: 75,hidden:true },
            { label: '', name: 'firstName_en', width: 75,hidden:true },
            { label: '', name: 'lastName_cn', width: 75,hidden:true },
            { label: '', name: 'firstName_cn',  width: 75,hidden:true },
            { label: '', name: 'sex', width: 75,hidden:true },
            { label: '', name: 'passageType',  width: 75,hidden:true },
            { label: '', name: 'docType',  width: 75,hidden:true },
            { label: '旅客姓名', name: 'Customer1', width: 70,
                formatter : function(value,ops,row){
                    var lastNameEn=row.lastName_en;
                    var firstNameEn=row.firstName_en;
                    return "<span>"+lastNameEn+"</span>"+"<span>"+firstNameEn+"</span>"
                } },
            { label: '中文姓名', name: 'Customer2', width: 70,
                formatter : function(value,ops,row){
                    var lastNamecn=row.lastName_cn;
                    var firstNamecn=row.firstName_cn;
                    return "<span>"+lastNamecn+"</span>"+"<span>"+firstNamecn+"</span>"
                }},
            { label: '性别', name: 'sex1', width: 40,
                formatter : function(value,ops,row){
                    if(row.sex ==2){
                        return "女";
                    }else if(row.sex==1){
                        return "男";
                    };
                }},
            { label:'旅客类型', name: 'passageType1', width: 70,
                formatter : function(value,ops,row){
                    if(row.passageType ==0){
                        return "婴儿";
                    }else if(row.passageType==1){
                        return "成人";
                    }else if(row.passageType == 2){
                        return "儿童";
                    };
                }},
            { label:'证件类别', name: 'docType1', width: 70,
                formatter : function(value,ops,row){
                    if(row.docType==1){
                        return "身份证 ";
                    }else if(row.docType == 2){
                        return "护照";
                    };
                }},
            { label:'证件号', name: 'docId', width: 100 },
            { label:'证件有效期', name: 'docExpireDate', width: 80 },
            { label:'出生日期', name: 'birthDate', width: 80 },
            { label:'手机号', name: 'mobile', width: 100 },
            { label:'国籍', name: 'nationality', width: 80 },
            { label:'签发国家', name: 'issueCountry', width: 80 },
            { label:'酒店', name: 'grogshop', width: 100 },
            { label:'联运', name: 'throughTraffic', width: 100 },
            { label:'备注', name: 'remark', width: 100 },
            { label:'操作', name: 'act', width: 70,
                formatter : function(value,ops, row) {
                    var str = '<a href="javascript:void(0)" onclick="editFun(\''+row.id+'\');" >修改</a>&nbsp;<a href="javascript:void(0)" onclick="delFun(\''+row.id+'\');" >删除</a>';
                    return str;
                }}
        ]
    });
    shouldPay();
});
//加载应付票款
function shouldPay(){
	$.ajax({
		type:"get",
		url:'${ctx}/order/payableTic/${orderNumber}?temp='+Math.random(),
		success:function(data){
			$("#payMoney").html(data.obj);
		}
	});
};
var purchQuantity = 0;
function initPage(b){
	$("#itineraryName").text(b.toStartAirport+"-"+b.toEndAirport);
	$("#periodDesc").text(b.travelDays);
	$("#payPrice").html(b.payPrice);
	//$("#unitPrice").html(b.unitPrice);
	$("#purchQuantity").html(b.purchQuantity);
	$("#payEndTime").html(b.payEndTime);
	$("#ticketEndTime").html(b.ticketEndTime);
	$("#ticketLoss").html(b.ticketLoss);
	$("#ticketRate").html(b.ticketRate);
	purchQuantity = b.purchQuantity;
	
	for(var n in b.flights){
		var f = b.flights[n];
		var seatClass = CommonConverter.toFlightCabinTypeStr(f.cabin);
        var temp = "";
        if(n==0){
            temp = "<td rowspan='2'><input type='text' id='price' style='border:none;text-align:center;' readonly='readonly' value='"+CommonConverter.formatMoney(b.unitPrice)+"'/></td>";
        }
		var i = n-0+1;
		$("#tbl_flights").append("<tr class='table_body'>"
			+"<td>"+i+"</td>"
			+"<td>"+f.flightNumber+"</td>"
			+"<td>"+seatClass+"</td>"
			+"<td>"+f.departureCity+"("+f.departureCode+")"+"-"+f.arrivalCity+"("+f.arrivalCode+")</td>"
			+"<td>"+f.departureDateStr+"</td>"
			+"<td>"+f.departureTime+"</td>"
			+"<td>"+f.arrivalTime + (f.intervalDay>0?("(+"+f.intervalDay+")"):"")+"</td>"
            +temp
			+"</tr>");
	}
};
function addFun(){
    var records = $("#jqGrid").jqGrid('getGridParam','records');
	if(records>=purchQuantity){
		layer.alert("旅客数量超出订票数量");
		return false;
	};
	layer.open({
		type: 2,
		 title: ['添加乘客信息','background-color:#00B2EE; color:#fff;'],
		shadeClose: false,
		shade: 0.3,
		closeBtn: 1, //显示关闭按钮
        fix: false,
		yes: function(index, layero) {
			layer.close(index);
		},
        area: ['600px', '550px'],
		content: ['${ctx}/order/toPassengerAdd/${orderNumber}', 'no'], //iframe的url，no代表不显示滚动条
		end:function(){
            $("#jqGrid").trigger("reloadGrid");
			 shouldPay();
		}
	});
};
function editFun(id){
	layer.open({
		type: 2,
        title: ['修改乘客信息','background-color:#00B2EE; color:#fff;'],
		shadeClose: false,
		shade: 0.3,
		closeBtn: 1, //显示关闭按钮
		yes: function(index, layero) {
			layer.close(index);
		},
        area: ['600px', '550px'],
		content: ['${ctx}/order/toPassengerEdit/'+id, 'no'], //iframe的url，no代表不显示滚动条
		end:function(){
            $("#jqGrid").trigger("reloadGrid");
			 shouldPay();
		}
	});
};
function delFun(id){
	$.ajax({
		type:'get',
		url:'${ctx}/order/delPassenger/'+id,
		dataType:'json',
		success:function(data){
			if(data.success){
                $("#jqGrid").trigger("reloadGrid");
				 shouldPay();
			}
			else{
				layer.alert(data.msg);
			}
		},
		error:function(msg){
			layer.alert("请检查您的网络连接，然后重试！");
		}
	}); 
};
//导入旅客
function importFun(){
    layer.open({
        type: 2,
        title: ['乘客导入','background-color:#00B2EE; color:#fff;'],
        shadeClose: false,
        shade: 0.3,
        fix: false,
        closeBtn: 1, //不显示关闭按钮
        yes: function(index, layero) {
            layer.close(index);
        },
        area: ['600px', '550px'],
        content: ['${ctx}/np/orderPassengerImp?orderNumber=${orderNumber}', 'no'], //iframe的url，no代表不显示滚动条
        end:function(){
            $("#jqGrid").trigger("reloadGrid");
            shouldPay();
        }
    });
};
function isRepeat(arr) {
	var hash = {};
	for ( var i in arr) {
		if (hash[arr[i]])
			return true;
		hash[arr[i]] = true;
	}
	return false;
};
function submitTicket() {
    var records = $("#jqGrid").jqGrid('getGridParam','records');
	if (records == 0) {
		layer.alert("请先填写旅客信息");
		return false;
	}
	var orderNos = new Array();
    var ids = $("#jqGrid").jqGrid('getDataIDs');
    for(var i=0;i<ids.length;i++){
        var id = ids[i];
        var row= $("#jqGrid").jqGrid("getRowData", id);
        orderNos.push(row.docType + row.docId);
    }
	if(isRepeat(orderNos)){
		layer.alert("旅客信息中证件号有重复数据，请确认");
		return false;
	}
	if (records > purchQuantity) {
		layer.alert("旅客数量超出订票数量");
		return false;
	}
	layer.load();
	var obj = {
		"orderNumber" : "${orderNumber}"
	}
	$.ajax({
		type : 'post',
		url : '${ctx}/order/orderTicket',
		contentType : 'application/json;charset=utf-8',
		data : JSON.stringify(obj),
		success : function(data) {
            layer.closeAll();
			if (data.success) {
				layer.alert('出票提交成功！', {
					skin : 'layui-layer-lan',
					title : [ '系统提示',
							'background-color:#00B2EE; color:#fff;' ],
					closeBtn : 0
				}, function(index) {
					window.location.href="${ctx}/np/toBeTicketing";
					layer.close(index);
				});
			} else {
				layer.alert(data.msg);
			}
		},
		error : function(msg) {
            layer.closeAll();
			layer.alert("请检查您的网络连接，然后重试！");
		}
	});
};
</script>
</head>
<body>
	<jsp:include page="../head.jsp"></jsp:include>
	<div class="divBox" >
			<!--航班信息-->
			<div class="cHeader">
				<img src="${ctx }/image/book/green.gif"/><span>航班信息</span>
			</div>
			<div class="cContent">
				<div class="ccHeader">
					<span id="itineraryName"></span>    <span id="periodDesc"></span>
				</div>
				<table class="tableInf" border="1" id="tbl_flights">
					<thead>
						<tr>
							<td style="width:51px">序号</td>
							<td style="width:105px">航班号</td>
							<td style="width:105px">仓位</td>
							<td style="width:544px">行程</td>
							<td style="width:103px">起飞日期</td>
							<td style="width:103px">出发时刻</td>
							<td style="width:103px">到达时刻</td>
							<td style="width:143px">单价含税（CNY/张）</td>
						</tr>
					</thead>
				</table>
				<!--旅客信息-->
				<ul class="cHeader passengerHeader">
					<li class="left"><img src="${ctx }/image/book/green.gif"/><span>旅客信息</span></li>
					<li class="right">
                        <button class="blueBtn left" onclick="importFun();">导入旅客</button>
                    <button class="blueBtn left" onclick="addFun();">添加旅客</button>&nbsp;
                    </li>
				</ul>
				<div class="passengerTab" >
                        <table id="jqGrid"></table>
				</div> 
				<!--操作-->
				<div class="priceBox">
					<p class="price">采购数量：<span id="purchQuantity">0</span>张&nbsp;&nbsp;&nbsp;支付金额<span class="font_money">￥&nbsp;<span id="payMoney" class="font_money">0.00</span></span></p>
					<p class="price">票损：<span id="ticketLoss">0</span>CNY/人&nbsp;&nbsp;&nbsp;出票率： <span class="font_money"><span id="ticketRate" class="font_money">0.00</span>%</span></p>
					<p class="timeLimit">支付时限：<span>审核通过后24小时&nbsp;&nbsp;&nbsp;</span>最晚出票时间:<span id="ticketEndTime">起飞前两天</span></p>
					<p class="operation">
						<button class="blueBtn yellow" onclick="submitTicket(this);">支付并下单</button>
					</p>
				</div>
			</div>
		</div>
 	<jsp:include page="../footer.jsp"></jsp:include>
</body>
</html>